package main

import (
	"fmt"
	"gopkg.in/yaml.v2"
	"io/ioutil"

	"github.com/spf13/viper"
)

type SMTPConfig struct {
	Host		string	`yaml:"host"`
	Username	string	`yaml:"username"`
	Password	string	`yaml:"password"`
}

type Configuration struct {
	DSN		string	`yaml:"dsn"`
	
	SMTP_Host	string	`yaml:"smtp_host"`
	SMTPUsername	string	`yaml:"smtp_usernane"`
	SMTPPassword	string	`yaml:"smtp_password"`

	QiniuBucket	string	`yaml:"qiniu_bucket"`
	QiniuAccessKey	string	`yaml:"qiniu_accesskey"`
	QiniuSecretKey	string	`yaml:"qiniu_secretkey"`
	Port		int	`yaml:"port"`
	SMTP		SMTPConfig	`yaml:"smtp"`
}


var (
	configuration *Configuration
)

func LoadConfiguration(path string) error {
	data, err := ioutil.ReadFile(path)
	if err != nil {
		return err
	}

	var config Configuration
	err = yaml.Unmarshal(data, &config)
	if err != nil {
		return err
	}

	fmt.Println("in func(yaml.v2): ", config)
	configuration = &config
	return nil
}

func LoadConfigurationV2() error {
	v := viper.New()
	v.AddConfigPath("./config/")
	v.SetConfigType("yaml")
	v.SetConfigName("config")

	if err := v.ReadInConfig(); err != nil {
		return err
	}
	

	var config Configuration
	if err := v.Unmarshal(&config); err != nil {
		return nil
	}

	fmt.Println("in func(viper): ", config)
	configuration = &config
	return nil
}


func GetConfiguration() *Configuration {
	return configuration
}

func main() {
	// path := "./config/config.yaml"
	// err := LoadConfiguration(path)
	err := LoadConfigurationV2()
	if err != nil {
		fmt.Println("Load configuration err ", err)
	}

	fmt.Println("in main: ", GetConfiguration().DSN)
	fmt.Println("in main: ", GetConfiguration().QiniuBucket)
	fmt.Println("in main: ", GetConfiguration().SMTP.Host)
}
